<template>
  <div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <!-- 日报 -->
      <el-tab-pane label="日报" name="daily">
        <!-- 搜索部分 -->
        <div class="tableSearch">
          <el-form size="mini" :model="ruleFormDaily" :rules="rulesDaily" ref="ruleFormDaily">
            <el-form-item label="门店：" label-width="80px" prop="shopId">
              <el-select v-model="ruleFormDaily.shopId" placeholder="请选择">
                <el-option
                  v-for="(item) in storeArrDaily"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="日期：" label-width="100px" prop="startDate">
              <el-date-picker
                v-model="ruleFormDaily.startDate"
                type="date"
                format="yyyy年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                placeholder="请选择"
                :picker-options="pickerOptions"
                style="width:180px;"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="商品分类：" label-width="120px">
              <el-cascader
                change-on-select
                expand-trigger="hover"
                v-model="ruleFormDaily.parentId"
                :options="optionsDaily"
                placeholder="请选择"
              ></el-cascader>
            </el-form-item>
            <el-form-item label label-width="35px">
              <el-button type="primary" @click="submitFormDaily('ruleFormDaily')">查询</el-button>
            </el-form-item>
            <el-form-item label label-width="15px">
              <el-button type="primary" v-if="setRole('导出')" @click="handleOutputDaily()">导出</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 门店汇总数据 -->
        <h3 class="store-summary">门店汇总数据：</h3>
        <el-form size="mini">
          <el-row>
            <el-col :span="8">
              <el-form-item label="商品销售数量：">
                <span>{{ resDataDaily.sumGoodsNum }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订单数量：">
                <span>{{ resDataDaily.sumOrderNum }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="会员订单数量：">
                <span>{{ resDataDaily.memberOrderNum }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="应收金额：">
                <span>{{ resDataDaily.sumShouldAmount }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="实收金额：">
                <span>{{ resDataDaily.sumGoodsAmount }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="平均客单件：">
                <span>{{ resDataDaily.sumAvgNum }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="平均客单价：">
                <span>{{ resDataDaily.sumAvgAmount }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 门店汇总数据-表格 -->
        <el-table v-show="tableDataDaily.length !== 0" :data="tableDataDaily">
          <el-table-column prop="goodsName" label="商品名称" align="center"></el-table-column>
          <el-table-column prop="primaryClassifyName" label="所属分类" align="center"></el-table-column>
          <el-table-column prop="goodsCount" label="商品销售数量" align="center"></el-table-column>
          <el-table-column prop="orderNum" label="订单数量" align="center"></el-table-column>
          <el-table-column prop="shouldAmount" label="应收金额" align="center"></el-table-column>
          <el-table-column prop="goodsAmount" label="实收金额" align="center"></el-table-column>
          <el-table-column prop="avgNum" label="平均客单件" align="center"></el-table-column>
          <el-table-column prop="avgAmount" label="平均客单价" align="center"></el-table-column>
        </el-table>
        <page-unit
          v-show="tableDataDaily.length !== 0"
          :pageData="pageDataDaily"
          :func="_shopSaleDaySumReport"
        ></page-unit>
      </el-tab-pane>

      <!-- 周报 -->
      <el-tab-pane label="周报" name="weekly">
        <!-- 搜索部分 -->
        <div class="tableSearch">
          <el-form size="mini" :model="ruleFormWeekly" ref="ruleFormWeekly">
            <el-form-item label="门店：" label-width="60px" prop="shopId">
              <el-select v-model="ruleFormWeekly.shopId" placeholder="请选择">
                <el-option
                  v-for="item in storeArrWeekly"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品分类：" label-width="120px">
              <el-cascader
                change-on-select
                expand-trigger="hover"
                :options="optionsWeekly"
                placeholder="请选择"
                @change="handleChangeWeekly"
                clearable
              ></el-cascader>
            </el-form-item>
            <el-form-item label label-width="35px">
              <el-button type="primary" @click="submitFormWeekly()">查询</el-button>
            </el-form-item>
            <el-form-item label label-width="15px">
              <el-button type="primary" v-if="setRole('导出')" @click="handleOutputWeekly()">导出</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 门店汇总数据 -->
        <h3 class="store-summary">
          门店汇总数据：
          <span>{{ruleFormWeekly.weekStart}}</span> ——
          <span>{{ruleFormWeekly.weekEnd}}</span>
        </h3>
        <el-form size="mini">
          <el-row>
            <el-col :span="8">
              <el-form-item label="商品销售数量：">
                <span>{{ resDataWeekly.sumGoodsNum }}</span>
                <span
                  v-bind:class="textColor(resDataWeekly.sumGoodsNumRatio) ? 'red' : 'green'"
                >{{ resDataWeekly.sumGoodsNumRatio }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订单数量：">
                <span>{{ resDataWeekly.sumOrderNum }}</span>
                <span
                  v-bind:class="textColor(resDataWeekly.sumOrderNumRatio) ? 'red' : 'green'"
                >{{ resDataWeekly.sumOrderNumRatio }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="会员订单数量：">
                <span>{{ resDataWeekly.memberOrderNum }}</span>
                <span
                  v-bind:class="textColor(resDataWeekly.memberOrderNumRatio) ? 'red' : 'green'"
                >{{resDataWeekly.memberOrderNumRatio}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-col :span="8">
            <el-form-item label="实收金额：">
              <span>{{ resDataWeekly.sumGoodsAmount }}</span>
              <span
                v-bind:class="textColor(resDataWeekly.sumGoodsAmountRatio) ? 'red' : 'green'"
              >{{ resDataWeekly.sumGoodsAmountRatio }}</span>
            </el-form-item>
          </el-col>
          <el-row>
            <el-col :span="8">
              <el-form-item label="应收金额：">
                <span>{{ resDataWeekly.sumShouldAmount }}</span>
                <span
                  v-bind:class="textColor(resDataWeekly.sumShouldAmountRatio) ? 'red' : 'green'"
                >{{ resDataWeekly.sumShouldAmountRatio }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="平均客单价：">
                <span>{{ resDataWeekly.sumAvgAmount }}</span>
                <span
                  v-bind:class="textColor(resDataWeekly.sumAvgAmountRatio) ? 'red' : 'green'"
                >{{ resDataWeekly.sumAvgAmountRatio }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="平均客单件：">
                <span>{{ resDataWeekly.sumAvgNum }}</span>
                <span
                  v-bind:class="textColor(resDataWeekly.sumAvgNumRatio) ? 'red' : 'green'"
                >{{ resDataWeekly.sumAvgNumRatio }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 门店汇总数据-表格 -->
        <el-table v-show="showList" :data="tableDataWeekly">
          <el-table-column prop="goodsName" label="商品名称" align="center"></el-table-column>
          <el-table-column prop="primaryClassifyName" label="商品分类" align="center" width="200"></el-table-column>
          <el-table-column prop="goodsCount" label="商品销售数量" align="center" width="150"></el-table-column>
          <el-table-column prop="goodsCountLastWeek" label="上周数量" align="center"></el-table-column>
          <el-table-column prop="goodsCountRatio" label="环比上周" align="center"></el-table-column>
          <el-table-column prop="orderNum" label="订单数量" align="center"></el-table-column>
          <el-table-column prop="orderNumLastWeek" label="上周数据" align="center"></el-table-column>
          <el-table-column prop="orderNumRatio" label="环比上周" align="center"></el-table-column>
          <el-table-column prop="shouldAmount" label="应收金额" align="center"></el-table-column>
          <el-table-column prop="shouldAmountLastWeek" label="上周数据" align="center"></el-table-column>
          <el-table-column prop="shouldAmountRatio" label="环比上周" align="center"></el-table-column>
          <el-table-column prop="goodsAmount" label="实收金额" align="center"></el-table-column>
          <el-table-column prop="goodsAmountLastWeek" label="上周数据" align="center"></el-table-column>
          <el-table-column prop="goodsAmountRatio" label="环比上周" align="center"></el-table-column>
          <el-table-column prop="avgNum" label="平均客单件" align="center" width="150"></el-table-column>
          <el-table-column prop="avgNumLastWeek" label="上周数据" align="center"></el-table-column>
          <el-table-column prop="avgNumRatio" label="环比上周" align="center"></el-table-column>
          <el-table-column prop="avgAmount" label="平均客单价" align="center" width="150"></el-table-column>
          <el-table-column prop="avgAmountLastWeek" label="上周数据" align="center"></el-table-column>
          <el-table-column prop="avgAmountRatio" label="环比上周" align="center"></el-table-column>
        </el-table>
        <page-unit v-show="showList" :pageData="pageDataWeekly" :func="_shopSaleWeekSumReport"></page-unit>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { mapState } from "vuex";
import pageUnit from "@/components/Page";
import dateClass from "@/util/date.js";
import u from "@/util";
import {
  getGoodsClassifyTreeList,
  selectBaseShopPageList,
  shopSaleDaySumReport,
  shopSaleWeekSumReport,
  exportShopSaleDaySumReport,
  exportShopSaleWeekSumReport // 导出
} from "@/api/index.js";
const date = new dateClass();
const fileDownload = require("js-file-download");

export default {
  computed: mapState(["sub", "merchantId", "power", "isShop", "linkName"]),
  components: { pageUnit },
  data() {
    return {
      showList: false,
      activeName: "daily", // tab激活项
      ruleFormDaily: {
        shopId: "", // ，门店id
        startDate: "", // 日期
        parentId: [""] // 商品分类id
      },
      ruleFormWeekly: {
        shopId: "",
        parentId: "",
        weekStart: "",
        weekEnd: ""
      },
      optionsDaily: [], // 商品分类数组
      optionsWeekly: [],
      storeArrDaily: [], // 门店数组
      storeArrWeekly: [],
      rulesDaily: {
        shopId: [
          { required: true, message: "请选择一个门店", trigger: "change" }
        ],
        startDate: [
          { required: true, message: "请选择日期", trigger: "change" }
        ]
      },
      tableDataDaily: [],
      tableDataWeekly: [],
      pageDataDaily: {
        pageSize: 10,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      },
      pageDataWeekly: {
        pageSize: 10,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      },
      resDataDaily: {},
      resDataWeekly: {},
      exportDataDaily: {}, // 导出数据条件
      exportDataWeekly: {},
      pickerOptions: {
        // 日期不能选当日及以后
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e7;
        }
      }
    };
  },
  mounted() {
    this.init();
    this._selectBaseShopPageList(); // 获取门店
    this._getGoodsClassifyTreeList(); // 获取商品分类
  },
  methods: {
    // 权限配置
    setRole(key) {
      return u.selectTitle(this.power, key);
    },
    textColor(value) {
      if (value) {
        let num = Number(value.split("%")[0]);
        if (num > 0) {
          return true;
        } else {
          return false;
        }
      }
    },

    // 初始化上周时间
    init() {
      this.ruleFormWeekly.weekStart = date.getLastWeekMonday();
      this.ruleFormWeekly.weekEnd = date.getLastWeekSunday();
    },

    // 获取门店
    _selectBaseShopPageList() {
      selectBaseShopPageList({
        businessId: this.merchantId,
        type: 3
      }).then(res => {
        let data = {
          id: "",
          name: "全部"
        };
        let isStore = {
          id: this.merchantId,
          name: this.linkName
        };
        this.storeArrDaily = JSON.parse(JSON.stringify(res.data.list));
        if (this.isShop == "0") {
          this.storeArrDaily.unshift(isStore);
          this.ruleFormDaily.shopId = isStore.id;
        }
        this.storeArrWeekly = JSON.parse(JSON.stringify(res.data.list));
        if (this.isShop == "0") {
          this.storeArrWeekly.unshift(isStore);
          this.ruleFormWeekly.shopId = isStore.id;
        } else {
          this.storeArrWeekly.unshift(data);
        }
      });
    },

    // 获取商品分类
    _getGoodsClassifyTreeList() {
      getGoodsClassifyTreeList().then(res => {
        let data = {
          value: "",
          label: "全部"
        };
        
        this.optionsDaily = JSON.parse(JSON.stringify(res.data));
        this.optionsDaily.unshift(data)
        this.optionsWeekly = JSON.parse(JSON.stringify(res.data));
      });
    },

    // 切换tab
    handleClick(tab, event) {
      if (tab.name == "weekly") {
        this._shopSaleWeekSumReport(this.pageDataWeekly.pageSize, 1);
      }
    },

    // 日报搜索
    submitFormDaily(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.pageDataDaily.currentPage = 1;
          this._shopSaleDaySumReport(
            this.pageDataDaily.pageSize,1
          );
        } else {
          return false;
        }
      });
    },

    // 周报搜索
    submitFormWeekly() {
      this.pageDataWeekly.currentPage = 1;
      this._shopSaleWeekSumReport(
        this.pageDataWeekly.pageSize,1
      );
    },

    // 根据条件获取日报统计表
    _shopSaleDaySumReport(pageSize, pageNum) {
      let postParentId = this.ruleFormDaily.parentId[this.ruleFormDaily.parentId.length-1] || '';
      let data = {
        startDate: this.ruleFormDaily.startDate,
        endDate: this.ruleFormDaily.startDate,
        shopId: this.ruleFormDaily.shopId,
        thisShopId: this.merchantId,
        parentId: postParentId,
        pageSize: pageSize,
        pageNum: pageNum
      };
      this.exportDataDaily = JSON.parse(JSON.stringify(data));
      shopSaleDaySumReport(data).then(res => {
        if (res.code == 200) {
          if (res.data !== null) {
            this.tableDataDaily = res.data.list;
            this.pageDataDaily.totalItems = res.data.totail;
            this.resDataDaily = res.data;
          } else {
            this.tableDataDaily = [];
            this.resDataDaily = [];
            this.$message.error("查询日期暂无交易记录！");
          }
        }
      });
    },

    // 根据条件获取周报统计表
    _shopSaleWeekSumReport(pageSize, pageNum) {
      if (this.ruleFormWeekly.parentId == undefined) {
        this.ruleFormWeekly.parentId = "";
      }
      let data = {
        startDate: this.ruleFormWeekly.weekStart,
        endDate: this.ruleFormWeekly.weekEnd,
        shopId: this.ruleFormWeekly.shopId,
        parentId: this.ruleFormWeekly.parentId,
        pageSize: pageSize,
        pageNum: pageNum,
        // thisShopId: 'shengdan_standard_001'
        thisShopId: this.merchantId
      };
      this.exportDataWeekly = JSON.parse(JSON.stringify(data));
      shopSaleWeekSumReport(data).then(res => {
        if (res.code == 200) {
          if (res.data !== null) {
            if (this.ruleFormWeekly.parentId === "") {
              this.tableDataWeekly = [];
              this.showList = false;
            } else {
              this.tableDataWeekly = res.data.list;
              this.showList = true;
            }
            this.pageDataWeekly.totalItems = res.data.totail;
            this.resDataWeekly = res.data;
          } else {
            this.tableDataWeekly = [];
            this.resDataWeekly = [];
            this.$message.error("查询日期暂无交易记录！");
          }
        }
      });
    },

    // change周报商品分类
    handleChangeWeekly(value) {
      this.ruleFormWeekly.parentId = value[value.length - 1];
    },

    // 日报导出
    handleOutputDaily() {
      if (this.tableDataDaily.length === 0) {
        this.$message.error("数据为空不能导出");
      } else {
        delete this.exportDataDaily.pageSize;
        delete this.exportDataDaily.pageNum;
        exportShopSaleDaySumReport(this.exportDataDaily).then(res => {
          let fileName = "门店销售统计表（日报）.xlsx";
          fileDownload(res, fileName);
        });
      }
    },

    // 周报导出
    handleOutputWeekly() {
      if (this.tableDataWeekly.length === 0) {
        this.$message.error("数据为空不能导出");
      } else {
        delete this.exportDataWeekly.pageSize;
        delete this.exportDataWeekly.pageNum;
        exportShopSaleWeekSumReport(this.exportDataWeekly).then(res => {
          let fileName = "门店销售统计表（周报）.xlsx";
          fileDownload(res, fileName);
        });
      }
    }
  }
};
</script>

<style lang="less" scoped>
.store-summary {
  height: 50px;
  line-height: 50px;
  border-top: solid 1px #666;
  margin-top: 20px;
  span {
    display: inline-block;
    font-size: 14px;
    font-weight: 500;
  }
}
.red {
  display: inline-block;
  width: 100px;
  text-align: center;
  color: red;
}
.green {
  display: inline-block;
  width: 100px;
  text-align: center;
  color: green;
}
</style>

